package com.huilian.iotbox.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.dao.OrderDao;
import com.huilian.iotbox.admin.service.ActivityOrderService;
import com.huilian.iotbox.admin.service.DeviceService;
import com.huilian.iotbox.admin.service.MerchantStoreService;
import com.huilian.iotbox.admin.service.OrderService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.config.AgencyConfig;
import com.huilian.iotbox.data.config.MiddlewareConfig;
import com.huilian.iotbox.data.dto.ActivityOrderDto;
import com.huilian.iotbox.data.dto.OrderDto;
import com.huilian.iotbox.data.enums.*;
import com.huilian.iotbox.data.po.ExternalDeviceParamValue;
import com.huilian.iotbox.data.po.MerchantStore;
import com.huilian.iotbox.data.po.Order;
import com.huilian.iotbox.data.properties.ConfigProperties;
import com.huilian.iotbox.data.properties.FileProperties;
import com.huilian.iotbox.data.service.LawHolidayService;
import com.huilian.iotbox.data.utils.*;
import com.huilian.iotbox.data.vo.ActivityOrderVo;
import com.huilian.iotbox.data.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author lizhiquan
 * @CreateDate: 2021-04-02-15-33
 * @Description:
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;
    @Autowired
    private AgencyConfig agencyConfig;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private FileProperties fileProperties;
    @Autowired
    private ConfigProperties configProperties;
    @Autowired
    private LawHolidayService lawHolidayService;
    @Autowired
    private MerchantStoreService merchantStoreService;
    @Autowired
    private ActivityOrderService activityOrderService;
    @Resource
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @Override
    public PageInfo findOrderList(OrderDto orderDto) {
        PageHelper.startPage(orderDto.getPageNum(), orderDto.getPageSize(), false);
        List<OrderVo> orderList = orderDao.findAdminOrderList(orderDto);
        PageInfo pagResult = new PageInfo(orderList);
        if (orderList.size() < 10) {
            pagResult.setTotal(orderDto.getPageSize() * orderDto.getPageNum());
        } else {
            pagResult.setTotal(orderDto.getPageSize() * orderDto.getPageNum() + 1);
        }
        return pagResult;
    }

    @Override
    public ServerResponse exportList(OrderDto orderDto) {
        //订单不限 只导出1,4,6,7,8,9
//        if (orderDto.getStatus() == -1) {
//            orderDto.setOrderStatusArray(new Integer[]{
//                    OrderStatusEnum.SUCCESS.getCode(),
//                    OrderStatusEnum.REFUND.getCode(),
//                    OrderStatusEnum.FULL_FERUND.getCode(),
//                    OrderStatusEnum.REFUNDING.getCode(),
//                    OrderStatusEnum.REFUND_FAIL.getCode()
//
//            });
//        }
        int count = orderDao.findExportTheQueryOrderCount(orderDto);
        if (count > 60000) {
            return ServerResponse.createByErrorMessage("导出数量超出了6万条，请缩小范围导出");
        }
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区为东八区
        // 格式化日期
        String formattedCreateTime = sdf.format(orderDto.getCreateTime());
        String formattedUpdateTime = sdf.format(orderDto.getUpdateTime());
        List<OrderVo> list = orderDao.findExportTheQueryOrderList(orderDto);
        String[] headers = new String[]{"支付类型", "门店名称", "订单号","第三方订单号", "设备号","设备备注名称", "设备类型", "编号", "商品", "金额（元）", "销售币", "赠送币", "总币", "订单状态","服务费","完成时间","操作人"};

        String sheetName = "普通订单" + formattedCreateTime + "至" + formattedUpdateTime;
        // 创建了一个excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(10);
        sheet.setColumnWidth(0, 30 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 25 * 256);
        sheet.setColumnWidth(3, 25 * 256);
        sheet.setColumnWidth(8, 25 * 256);
//        sheet.createFreezePane(0, 4, 0, 4);
        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font font = wb.createFont();
        //设置字体样式
        //font.setFontHeightInPoints((short) 20);   //--->设置字体大小
        font.setFontName("Courier New");   //---》设置字体，是什么类型例如：宋体
        font.setItalic(true);     //--->设置是否是加粗
        titleStyle.setFont(font);     //--->将字体格式加入到style1中
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直

        //内容样式
        HSSFCellStyle contextStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font contextfont = wb.createFont();
        contextfont.setFontHeightInPoints((short) 13);   //--->设置字体大小
        //设置字体样式
        contextStyle.setFont(contextfont);     //--->将字体格式加入到style1中
        contextStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        contextStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直
        contextStyle.setWrapText(true);//设置自动换行

        //表格第一行
        HSSFRow row1 = sheet.createRow(0);   //--->创建一行
        row1.setHeightInPoints(20);
        HSSFCell cell1 = row1.createCell(0);   //--->创建一个单元格
        // cell1.setCellStyle(titleStyle);
        cell1.setCellValue("普通订单记录");
        //表格第二行
        HSSFRow r2 = sheet.createRow(1);
        r2.setHeightInPoints(20);
        HSSFCell c2 = r2.createCell(0);
        c2.setCellValue("起始时间：[" + sdf.format(orderDto.getCreateTime()) + "]  " + "  终止时间：[" + sdf.format(orderDto.getUpdateTime()) + "]");
        //表格第三行
        HSSFRow r3 = sheet.createRow(2);
        r3.setHeightInPoints(20);
        HSSFCell c3 = r3.createCell(0);
        //c3.setCellValue("合计：" + "   交易总金额:" + statistic.getTradingTotal() + "   交易总笔数:" + statistic.getStrokeCount() + "   应结算总金额:" + statistic.getSettlementTotal() + "   已结算总金额:" + statistic.getStmtTotal() + "   手续费:" + statistic.getHandlingCharge());

        //标题
        HSSFRow row2 = sheet.createRow(3);           //--->创建一行
        contextStyle.setFillForegroundColor(HSSFColor.LEMON_CHIFFON.index);// 设置背景色
        contextStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        contextStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        contextStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        contextStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        contextStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        contextfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
        contextStyle.setFont(contextfont);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell2 = row2.createCell(i);
            cell2.setCellValue(headers[i]);
            cell2.setCellStyle(contextStyle);
        }

        int index = 0;//记录额外创建的sheet数量
        int j = 0;
        // 循环每行
        for (int i = 4; i < list.size() + 4; i++) {
            if ((i) % 65500 == 0) {
                sheet = wb.createSheet("salesList" + index);
                index++;
            }
            // 创建行
            HSSFRow row = sheet.createRow((i) - (index * 65500));
            // 创建列
            HSSFCell contextCell1 = row.createCell(0);

            if (!StringUtils.isEmpty(MchTypeEnum.getDesc(list.get(j).getMchType()))) {
                contextCell1.setCellValue(MchTypeEnum.getDesc(list.get(j).getMchType()));
            } else {
                contextCell1.setCellValue("");
            }
            HSSFCell contextCell2 = row.createCell(1);
            contextCell2.setCellValue(list.get(j).getStoreName());
            HSSFCell contextCell3 = row.createCell(2);
            contextCell3.setCellValue(list.get(j).getOutTradeNo());
            HSSFCell contextCell4 = row.createCell(3);
            contextCell4.setCellValue(list.get(j).getPayChannelOrderNo());
            HSSFCell contextCell13 = row.createCell(4);
            contextCell13.setCellValue(list.get(j).getDeviceNo());
            HSSFCell contextCell14 = row.createCell(5);
            contextCell14.setCellValue(list.get(j).getRemarkName());
            HSSFCell contextCell5 = row.createCell(6);
            DeviceTypeEnum device = DeviceTypeEnum.getDeviceTypeId(list.get(j).getDeviceTypeId());
            if (!StringUtils.isEmpty(device)) {
                contextCell5.setCellValue(device.getDesc());
            } else {
                contextCell5.setCellValue("");
            }
            HSSFCell contextCell6 = row.createCell(7);
            if (!StringUtils.isEmpty(list.get(j).getDeviceAlias())) {
                contextCell6.setCellValue(list.get(j).getDeviceAlias());
            } else {
                contextCell6.setCellValue("");
            }
            HSSFCell contextCell7 = row.createCell(8);
            if (!StringUtils.isEmpty(list.get(j).getBody())) {
                contextCell7.setCellValue(list.get(j).getBody());
            } else {
                contextCell7.setCellValue("");
            }
            HSSFCell contextCell8 = row.createCell(9);
            if (!ObjectUtils.isEmpty(list.get(j).getTotalAmount())) {
                contextCell8.setCellValue(list.get(j).getTotalAmount().toString());
            } else {
                contextCell8.setCellValue("");
            }
            HSSFCell contextCell9 = row.createCell(10);
            if (!ObjectUtils.isEmpty(list.get(j).getSaleCoin())) {
                contextCell9.setCellValue(list.get(j).getSaleCoin());
            } else {
                contextCell9.setCellValue("");
            }
            HSSFCell contextCell10 = row.createCell(11);
            if (!ObjectUtils.isEmpty(list.get(j).getGiveCoin())) {
                contextCell10.setCellValue(list.get(j).getGiveCoin());
            } else {
                contextCell10.setCellValue("");
            }
            HSSFCell contextCell11 = row.createCell(12);
            if (!ObjectUtils.isEmpty(list.get(j).getTotalCoin())) {
                contextCell11.setCellValue(list.get(j).getTotalCoin());
            } else {
                contextCell11.setCellValue("");
            }
            HSSFCell contextCell12 = row.createCell(13);
            contextCell12.setCellValue(OrderStatusEnum.formatDesc(list.get(j).getStatus()));

            HSSFCell contextCellHandlingCharge = row.createCell(14);
            if (!ObjectUtils.isEmpty(list.get(j).getHandlingCharge())) {
                contextCellHandlingCharge.setCellValue(list.get(j).getHandlingCharge().toString());
            } else {
                contextCellHandlingCharge.setCellValue("");
            }

            HSSFCell contextCell15= row.createCell(15);
            if (!StringUtils.isEmpty(list.get(j).getGmtPayment())){
                contextCell15.setCellValue(sdf.format(list.get(j).getGmtPayment()));
            }else{
                contextCell15.setCellValue("");
            }

            //运营商
            String operationName = "";
            HSSFCell contextCell16 = row.createCell(16);
            if (!StringUtils.isEmpty(list.get(j).getOperationName()) || !StringUtils.isEmpty(list.get(j).getOperationNickName())) {
                operationName = !StringUtils.isEmpty(list.get(j).getOperationName())?list.get(j).getOperationName():list.get(j).getOperationNickName() + ":";
                contextCell16.setCellValue(!StringUtils.isEmpty(list.get(j).getOperationName())?list.get(j).getOperationName():list.get(j).getOperationNickName());
            } else {
                contextCell16.setCellValue("");
            }
            if(!StringUtils.isEmpty(list.get(j).getOperationUserName())){
                contextCell16.setCellValue(operationName + list.get(j).getOperationUserName());
            }

            j++;
            if (j >= list.size()) {
                j = 0;
            }
        }
        // 保存文件
        FileOutputStream fileOut = null;
        String fileName = fileProperties.getSaveImgPath() + "/" + sheetName + ".xls";

        try {
            File f = new File(fileName);
            if (!f.exists()) {
                f.createNewFile();
            }
            // 文件保存的地址和名称
            log.info("------------------------------iot后台销售订单导出:" + fileName);
            fileOut = new FileOutputStream(fileName);
            wb.write(fileOut);

        } catch (IOException e) {
            // 处理文件操作可能发生的IO异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存失败:" + e + fileProperties.getSaveImgPath());
        } catch (Exception e) {
            // 其他异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存过程中发生了错误:" + e);

        } finally {
            // 关闭流
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Map<String, String> map = new HashMap<>();
        map.put("fileName", sheetName + ".xls");
        map.put("downloadUrl",configProperties.getAdminBackEndUrl() + "/api/fileExport/download/" +sheetName + ".xls");
        return ServerResponse.createBySuccess(map);
    }

    /**
     * 订单查询-汇总
     *
     * @param orderDto
     * @return
     * @throws Exception
     */
    @Override
    public ServerResponse findOrderStatistics(OrderDto orderDto) throws Exception {
        //非商户限制时间间隔
        if (
                StringUtils.isEmpty(orderDto.getCreateTime())
                        && StringUtils.isEmpty(orderDto.getUpdateTime())
                        && StringUtils.isEmpty(orderDto.getGmtPaymentStart())
                        && StringUtils.isEmpty(orderDto.getGmtPaymentEnd())
        ) {
            return ServerResponse.createByErrorMessage("下单时间、支付时间必须其中一个范围");
        }

        if (!StringUtils.isEmpty(orderDto.getCreateTime()) && StringUtils.isEmpty(orderDto.getUpdateTime())) {
            return ServerResponse.createByErrorMessage("必选下单结束时间");
        }
        if (StringUtils.isEmpty(orderDto.getCreateTime()) && !StringUtils.isEmpty(orderDto.getUpdateTime())) {
            return ServerResponse.createByErrorMessage("必选下单开始时间");
        }
        if (!StringUtils.isEmpty(orderDto.getCreateTime()) && !StringUtils.isEmpty(orderDto.getUpdateTime())) {
            boolean isOk = compareReqTimeSection(orderDto.getCreateTime(), orderDto.getUpdateTime());
            if (!isOk) {
                return ServerResponse.createByErrorMessage("请求异常，下单汇总时间间隔建议在24小时内");
            }
        }

        if (!StringUtils.isEmpty(orderDto.getGmtPaymentStart()) && StringUtils.isEmpty(orderDto.getGmtPaymentEnd())) {
            return ServerResponse.createByErrorMessage("必选支付结束时间");
        }
        if (StringUtils.isEmpty(orderDto.getGmtPaymentStart()) && !StringUtils.isEmpty(orderDto.getGmtPaymentEnd())) {
            return ServerResponse.createByErrorMessage("必选支付开始时间");
        }
        if (!StringUtils.isEmpty(orderDto.getGmtPaymentStart()) && !StringUtils.isEmpty(orderDto.getGmtPaymentEnd())) {
            boolean isOk = compareReqTimeSection(orderDto.getGmtPaymentStart(), orderDto.getGmtPaymentEnd());
            if (!isOk) {
                return ServerResponse.createByErrorMessage("请求异常，支付汇总时间间隔建议在24小时内");
            }
        }


        OrderVo orderVo = orderDao.findAdminOrderStatistics(orderDto);
        if (StringUtils.isEmpty(orderVo)) {
            return ServerResponse.createBySuccess("");
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(orderVo.getCreateTime());
        calendar.add(Calendar.DATE, 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(calendar.getTime());
        Boolean flag = lawHolidayService.isHoliday(date);
        if (flag) {
            BigDecimal fee = new BigDecimal("0.0002");
            BigDecimal settlementFee = SciCalUtils.sciCalToBD(orderVo.getSettlementTotal().multiply(fee), 2);
            orderVo.setSettlementTotal(orderVo.getSettlementTotal().subtract(settlementFee));
            orderVo.setFeeMoney(orderVo.getFeeMoney());
            orderVo.setTlementFee(settlementFee);
        }
        return ServerResponse.createBySuccess(orderVo);
    }

    private boolean compareReqTimeSection(Date beginTime, Date endTime) {
        Calendar calendar = Calendar.getInstance(); //得到日历
        if (beginTime == null) {
            return false;
        }
        calendar.setTime(beginTime);//把当前时间赋给日历
        calendar.add(Calendar.HOUR, 24);
        beginTime = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int i = beginTime.compareTo(endTime);
        if (i >= 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public OrderVo findCountDay(OrderDto orderDto) {
        // 获取当前的支付机构号 11156为金总  11155为莫总
        orderDto.setStartTime(DateTimeUtils.getTodayStartTime());
        orderDto.setEndTime(DateTimeUtils.getTodayEndTime());
        orderDto.setIsvOrgId(agencyConfig.getIsvOrgId());
        OrderVo countDay = orderDao.findCountDay(orderDto);

        ActivityOrderDto activityOrderDto = new ActivityOrderDto();
        activityOrderDto.setStartTime(DateTimeUtils.getTodayStartTime());
        activityOrderDto.setEndTime(DateTimeUtils.getTodayEndTime());
        activityOrderDto.setIsvOrgId(agencyConfig.getIsvOrgId());
        activityOrderDto.setUserInfo(orderDto.getUserInfo());
        ActivityOrderVo activityOrderVo = activityOrderService.findCountDay(activityOrderDto);


        if (orderDto.getUserInfo().getId().compareTo(172) == 0) {
            //定义50倍
            BigDecimal num = new BigDecimal(50);
            //总销售额乘50
            countDay.setTotalAmountCount((countDay.getTotalAmountCount().add(activityOrderVo.getTotalAmountCount())).multiply(num));
            //总交易笔数乘50
            countDay.setTotalCount((countDay.getTotalCount() + activityOrderVo.getTotalCount()) * 50);
            //总利润乘50
            countDay.setRealCommissionCount((countDay.getRealCommissionCount().add(activityOrderVo.getRealCommissionCount())).multiply(num));
            //总销量(游戏币) 乘 50
            countDay.setTotalCoinCount((countDay.getTotalCoinCount() + activityOrderVo.getTotalCoinCount()) * 50);
        } else {
            countDay.setTotalAmountCount(countDay.getTotalAmountCount().add(activityOrderVo.getTotalAmountCount()));
            countDay.setTotalCount(countDay.getTotalCount() + activityOrderVo.getTotalCount());
            countDay.setRealCommissionCount(countDay.getRealCommissionCount().add(activityOrderVo.getRealCommissionCount()));
            countDay.setTotalCoinCount(countDay.getTotalCoinCount() + activityOrderVo.getTotalCoinCount());
        }
        return countDay;
    }

    @Override
    public List<OrderVo> findDateOrder(Integer agencyId, String startTime, String endTime) {
        return orderDao.findDateOrder(agencyId, startTime, endTime);
    }

    @Override
    public Integer updateStatusById(OrderDto order) {
        return orderDao.updateStatusById(order);
    }

    @Override
    public OrderDto getById(Long orderId) {
        return orderDao.getById(orderId);
    }

    @Override
    public Order findOldOrder(Long orderId) {
        return orderDao.findOldOrder(orderId);
    }

    @Override
    public Integer delete(String endTime) {
        return orderDao.delete(endTime);
    }

    @Override
    public OrderVo findSuccessTotalAmount(OrderDto orderDto) {
        return orderDao.findSuccessTotalAmount(orderDto);
    }

    @Override
    public Integer insert(OrderDto order) {
        return orderDao.insert(order);
    }

    @Override
    public List<OrderVo> findSuccessTotalAmountList(OrderDto orderDto) {
        return orderDao.findSuccessTotalAmountList(orderDto);
    }

    @Override
    public OrderDto intendpay(Integer subDeviceId, Integer positionId, Integer times, String deviceNo) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        OrderDto orderDto = new OrderDto();
        orderDto.setDeviceNo(deviceNo);
        orderDto.setOutTradeNo(Util.getOutTradeNoNdj());
        orderDto.setOptionType(OrderOptionTypeEnum.ANDROID_NDJ.getCode());
        orderDto.setRechargeAfterBalance(0);
        orderDto.setSaleCoin(0);
        orderDto.setGiveCoin(0);
        orderDto.setTimes(times);
        orderDto.setTotalCoin(orderDto.getSaleCoin() + orderDto.getGiveCoin());

        MerchantStore merchantStore = merchantStoreService.findMerchantStoreByDeviceNo(deviceNo);
        orderDto.setMchType(MchTypeEnum.OWN.getCode());
        orderDto.setMerchantStoreId(merchantStore.getId());
        orderDto.setUserId(merchantStore.getUserId());
        orderDto.setMerchantId(merchantStore.getMerchantId());
        orderDto.setPayCompanyCode(merchantStore.getPayCompanyCode());
        orderDto.setStatus(OrderStatusEnum.WAIT.getCode());
        orderDto.setFunction(OrderFunctionEnum.OFFICIAL.getStatus());

        orderDto.setBody("购买直接启动设备");
        orderDao.insert(orderDto);


        Map<String, Object> form = new HashMap<>();
        form.put("outTradeNo", orderDto.getOutTradeNo());
        form.put("WxAppId", MiddlewareConfig.WX_APPID);
        form.put("Body", orderDto.getBody());
        form.put("HlMerchantId", orderDto.getMerchantId());
        form.put("NotifyUrl", configProperties.getClientBackEndUrl() + "/client/api/order/payNotice");
        form.put("ChannelType", orderDto.getChannelType());
        String param = HttpUtils.format(agencyConfig, form, FunctionEnum.SIMPLE_PAY);
        String response = HttpsMain.httpsReq(MiddlewareConfig.reqUrl + "/pay", param);
        log.info("请求响应结果{}", response);
        //延签并返回map值
        final Map<String, Object> result = HttpUtils.getResultData(response);
        final String status = (String) result.get("status");
        final String code = (String) result.get("code");
        if (status.equals(RequestStatus.SUCCESS.getCode()) && code.equals(RequestStatus.SUCCESS_CODE.getCode())) {
            final JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(result.get("data")));
            //orderDto
            orderDto.setQrCodeUrl(jsonObject.getString("qrCodeUrl"));
        }
        return orderDto;
    }

    @Override
    public Order findOneOrderByCondition(Order condition) {
        if (StringUtils.isEmpty(condition)) {
            return null;
        }
        return orderDao.findOneOrderByCondition(condition);
    }

    /**
     * 统计单个兑币机设备在一天里每个面额命中的次数
     *
     * @param orderDenomination
     * @return
     */
    @Override
    public List<OrderVo> findDenominationCountByDeviceNo(OrderDto orderDenomination) {
        return orderDao.findDenominationCountByDeviceNo(orderDenomination);
    }

    /**
     * 查询有哪些兑币机设备在一天有纸钞记录的
     *
     * @param orderDenomination
     * @return
     */
    @Override
    public List<OrderVo> findTurnoverOfflineGroupByDeviceNo(OrderDto orderDenomination) {
        return orderDao.findTurnoverOfflineGroupByDeviceNo(orderDenomination);
    }

    public String formatDateStr() {
        SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String datetime = tempDate.format(new Date());
        datetime = datetime.replace("-", "").replace(" ", "").replace(":", "");
        return datetime;
    }

    /**
     * 修改订单表数据, 抖音回调那边使用
     */
    @Override
    public Integer updateOrderDouYinData(OrderDto orderDto) {
        Integer result = orderDao.updateOrderDouYinData(orderDto);
        return result;
    }

    /**
     * 修改订单表数据, 抖音回调那边使用
     */
    @Override
    public Integer deleteOrderById(Long id) {
        Integer result = orderDao.deleteOrderById(id);
        return result;
    }

    /**
     * 修改订单表数据, 抖音回调那边使用
     */
    @Override
    public OrderVo findOrderOneByOutTradeNo(String outTradeNo) {
        OrderVo orderVo = orderDao.findOrderOneByOutTradeNo(outTradeNo);
        return orderVo;
    }

    @Override
    public OrderVo getOneOrderByDeviceNo(String deviceNo, Integer userId, Integer merchantStoreId) {
        return orderDao.getOneOrderByDeviceNo(deviceNo, userId, merchantStoreId);
    }
}
